/* eslint-disable operator-linebreak */
/* eslint-disable react/no-danger */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { useMemo, useState } from 'react';
import { Card, Row, Col, Button, Input, Form, Select, Tabs, message } from 'antd';
import hljs from 'highlight.js';
import { CopyTwoTone, EditOutlined } from '@ant-design/icons';
import MarkdownIt from 'markdown-it';
import DefineColumns from './components/DefineColumns';
import DefineItemType from './components/DefineItemType';
import 'highlight.js/styles/atom-one-light.css';
import './index.less';

const { Option } = Select;

const mdParser = MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value;
      } catch (error) {
        // eslint-disable-next-line no-console
        console.log(error);
      }
    }
    return ''; // 使用额外的默认转义
  },
});

const immutableCode =
  '```js' +
  `

  import { FC, useEffect } from 'react';
  import { Card, Table } from 'antd';
  import { ColumnsType } from 'antd/es/table';
  import useMakeList, { IParams } from './hooks/useMakeList';
`;

export default function AutoCoding() {
  const [form] = Form.useForm<{ itemType: any[]; columns: any[] }>();
  const [activeKey, setActiveKey] = useState('defineType');
  const [produceCode, setProduceCode] = useState(Date.now());

  const templateCode = useMemo<string>(() => {
    const { itemType = [], columns = [] } = form.getFieldsValue();
    return `${immutableCode}
  type ItemType = {
        ${itemType
          .map(item => {
            const { attr, type } = item;
            return `${attr}: ${type},\n`;
          })
          .join('\t')}  };
  const columns: ColumnsType<ItemType> = [
        ${columns
          .map(item => {
            const copyItem = { ...item };
            delete copyItem.index;
            delete copyItem.id;
            return JSON.stringify(copyItem);
          })
          .join(',')
          ?.replace(/},{/g, '},\n\t{')
          ?.replace(/[:,]/g, '$& ')}
  ];
  const Index: FC = () => {
    const { loading, list, getList, paginationConfig } = useMakeList<ItemType, { }>({
      params: {
        type: 1,
      },
      api: {
        getList: (params: IParams) => Promise.resolve(any),
      },
    });

    useEffect(() => getList(), []);
    return (
      <Card>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={list}
          loading={loading}
          pagination={paginationConfig}
          />
      </Card>
    );
  };
  export default Index;`;
  }, [produceCode]);

  const handleCopy = () => {
    navigator.clipboard.writeText(templateCode.replace('```js', ''));
    message.destroy();
    message.success('复制成功～');
  };

  const handleTabChange = (key: string) => {
    setActiveKey(key);
  };

  return (
    <Card>
      <Row gutter={48}>
        <Col span={12}>
          <Form form={form}>
            <Tabs onChange={handleTabChange} activeKey={activeKey}>
              <Tabs.TabPane tab="类型定义" key="defineType">
                <Form.Item name="itemType" label="" initialValue={[]}>
                  <DefineItemType />
                </Form.Item>
              </Tabs.TabPane>
              <Tabs.TabPane tab="Columns定义" key="defineColumns">
                <Form.Item name="columns" label="" initialValue={[]}>
                  <DefineColumns />
                </Form.Item>
              </Tabs.TabPane>
            </Tabs>
          </Form>
        </Col>
        <Col span={12}>
          <Button
            onClick={() => {
              setProduceCode(Date.now());
            }}
            icon={<EditOutlined />}
            style={{ marginRight: 40 }}
          >
            生成代码
          </Button>
          <Button
            icon={<CopyTwoTone twoToneColor="#ccc" />}
            onClick={handleCopy}
            style={{ marginBottom: 12 }}
          >
            一键复制
          </Button>
          <div
            className="code-wrapper"
            dangerouslySetInnerHTML={{
              __html: mdParser.render(templateCode),
            }}
          />
        </Col>
      </Row>
    </Card>
  );
}
